// IP/MAC限制管理JavaScript代码

var selectedIpRuleIndex = -1;
var selectedMacRuleIndex = -1;

// 确保在页面加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
        console.log('DOM加载完成，IP/MAC限制功能已就绪');
    });
} else {
    console.log('页面已加载，IP/MAC限制功能已就绪');
}

function loadRestriction() {
    var container = document.getElementById('tab-restriction');
    if (!container) {
        console.error('找不到 tab-restriction 容器');
        return;
    }
    
    // 确保容器可见
    container.style.display = 'block';
    
    // 只更新内容区域，保留外层div结构
    var ipRulesList = document.getElementById('ipRulesList');
    var macRulesList = document.getElementById('macRulesList');
    
    if (!ipRulesList || !macRulesList) {
        console.error('找不到规则列表容器，ipRulesList:', ipRulesList, 'macRulesList:', macRulesList);
        // 如果元素不存在，可能是HTML还没加载完成，等待一下再试
        setTimeout(function() {
            loadRestriction();
        }, 100);
        return;
    }
    
    if (ipRulesList) {
        ipRulesList.innerHTML = '<div class="loading"><div class="spinner"></div><p>正在加载...</p></div>';
    }
    if (macRulesList) {
        macRulesList.innerHTML = '<div class="loading"><div class="spinner"></div><p>正在加载...</p></div>';
    }
    
    var apiBase = typeof getSystemApiBase === 'function' ? getSystemApiBase() : '/api/system';
    console.log('调用API:', apiBase + '/restriction');
    
    fetch(apiBase + '/restriction')
        .then(function(response) {
            console.log('API响应状态:', response.status);
            if (!response.ok) {
                return response.text().then(function(text) {
                    console.error('API错误响应:', text);
                    throw new Error('HTTP ' + response.status + ': ' + text);
                });
            }
            return response.json();
        })
        .then(function(data) {
            console.log('API返回数据:', data);
            renderRestriction(data);
        })
        .catch(function(error) {
            console.error('加载IP/MAC限制配置失败：', error);
            var errorText = (error.message || '未知错误').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
            var errorMsg = '<div class="error" style="padding: 20px; color: #dc3545; text-align: center;">加载IP/MAC限制配置失败：' + errorText + '</div>';
            if (ipRulesList) ipRulesList.innerHTML = errorMsg;
            if (macRulesList) macRulesList.innerHTML = errorMsg;
        });
}

function renderRestriction(data) {
    try {
        var enabled = data.enabled || false;
        var whitelistMode = data.whitelistMode || false;
        var ipRules = data.ipRules || [];
        var macRules = data.macRules || [];
        
        // 更新复选框和单选按钮
        var chkEnable = document.getElementById('chkEnableRestriction');
        if (chkEnable) {
            chkEnable.checked = enabled;
        }
        
        var blacklistRadio = document.querySelector('#tab-restriction input[name="restrictionMode"][value="blacklist"]');
        var whitelistRadio = document.querySelector('#tab-restriction input[name="restrictionMode"][value="whitelist"]');
        if (blacklistRadio) blacklistRadio.checked = !whitelistMode;
        if (whitelistRadio) whitelistRadio.checked = whitelistMode;
        
        // 更新控件状态
        updateRestrictionControlsState(enabled);
        
        // 渲染IP规则列表
        renderIpRulesList(ipRules);
        
        // 渲染MAC规则列表
        renderMacRulesList(macRules);
    } catch (error) {
        console.error('渲染限制配置失败：', error);
        var container = document.getElementById('tab-restriction');
        if (container) {
            container.innerHTML = '<div class="error" style="padding: 20px; color: #dc3545;">渲染配置失败：' + escapeHtml(error.message) + '</div>';
        }
    }
}

function updateRestrictionControlsState(enabled) {
    var controls = document.querySelectorAll('#tab-restriction input[type="radio"], #tab-restriction button, #tab-restriction table');
    controls.forEach(function(ctrl) {
        ctrl.disabled = !enabled;
    });
}

function renderIpRulesList(ipRules) {
    var container = document.getElementById('ipRulesList');
    var countElement = document.getElementById('ipRulesCount');
    var removeBtn = document.getElementById('btnRemoveIpRule');
    
    if (!container) {
        console.error('找不到 ipRulesList 容器');
        return;
    }
    
    if (countElement) {
        countElement.textContent = ipRules.length + ' 条';
    }
    
    if (removeBtn) {
        removeBtn.disabled = ipRules.length === 0;
    }
    
    if (ipRules.length === 0) {
        container.innerHTML = '<div style="text-align: center; padding: 40px 20px; color: #9ca3af;"><div style="font-size: 48px; margin-bottom: 12px; opacity: 0.3;">📋</div><p style="margin: 0; font-size: 14px;">暂无 IP 规则</p><p style="margin: 8px 0 0 0; font-size: 12px; color: #d1d5db;">点击上方按钮添加规则</p></div>';
        selectedIpRuleIndex = -1;
        return;
    }
    
    var html = '<div style="padding: 8px;">';
    for (var i = 0; i < ipRules.length; i++) {
        var rule = ipRules[i] || '';
        var escapedRule = rule.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
        var isSelected = selectedIpRuleIndex === i;
        html += '<div onclick="selectIpRuleRow(this, ' + i + ')" style="cursor: pointer; padding: 12px; margin-bottom: 8px; background: ' + (isSelected ? '#e0e7ff' : 'white') + '; border: 1px solid ' + (isSelected ? '#667eea' : '#e5e7eb') + '; border-radius: 6px; transition: all 0.2s; display: flex; align-items: center; justify-content: space-between;" onmouseover="if(!this.classList.contains(\'selected\')) this.style.borderColor=\'#c7d2fe\'; this.style.background=\'' + (isSelected ? '#e0e7ff' : '#f9fafb') + '\';" onmouseout="if(!this.classList.contains(\'selected\')) this.style.borderColor=\'#e5e7eb\'; this.style.background=\'' + (isSelected ? '#e0e7ff' : 'white') + '\';" class="' + (isSelected ? 'selected' : '') + '">';
        html += '<div style="flex: 1;"><span style="display: inline-block; width: 24px; height: 24px; line-height: 24px; text-align: center; background: #f3f4f6; border-radius: 4px; margin-right: 12px; font-size: 12px; font-weight: 600; color: #6b7280;">' + (i + 1) + '</span>';
        html += '<code style="background: #f9fafb; padding: 4px 8px; border-radius: 4px; font-size: 13px; font-family: \'Consolas\', \'Monaco\', monospace; color: #1f2937;">' + escapedRule + '</code></div>';
        html += '</div>';
    }
    html += '</div>';
    
    container.innerHTML = html;
}

function renderMacRulesList(macRules) {
    var container = document.getElementById('macRulesList');
    var countElement = document.getElementById('macRulesCount');
    var removeBtn = document.getElementById('btnRemoveMacRule');
    
    if (!container) {
        console.error('找不到 macRulesList 容器');
        return;
    }
    
    if (countElement) {
        countElement.textContent = macRules.length + ' 条';
    }
    
    if (removeBtn) {
        removeBtn.disabled = macRules.length === 0;
    }
    
    if (macRules.length === 0) {
        container.innerHTML = '<div style="text-align: center; padding: 40px 20px; color: #9ca3af;"><div style="font-size: 48px; margin-bottom: 12px; opacity: 0.3;">📋</div><p style="margin: 0; font-size: 14px;">暂无 MAC 规则</p><p style="margin: 8px 0 0 0; font-size: 12px; color: #d1d5db;">点击上方按钮添加规则</p></div>';
        selectedMacRuleIndex = -1;
        return;
    }
    
    var html = '<div style="padding: 8px;">';
    for (var i = 0; i < macRules.length; i++) {
        var rule = macRules[i] || '';
        var escapedRule = rule.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
        var isSelected = selectedMacRuleIndex === i;
        html += '<div onclick="selectMacRuleRow(this, ' + i + ')" style="cursor: pointer; padding: 12px; margin-bottom: 8px; background: ' + (isSelected ? '#e0e7ff' : 'white') + '; border: 1px solid ' + (isSelected ? '#667eea' : '#e5e7eb') + '; border-radius: 6px; transition: all 0.2s; display: flex; align-items: center; justify-content: space-between;" onmouseover="if(!this.classList.contains(\'selected\')) this.style.borderColor=\'#c7d2fe\'; this.style.background=\'' + (isSelected ? '#e0e7ff' : '#f9fafb') + '\';" onmouseout="if(!this.classList.contains(\'selected\')) this.style.borderColor=\'#e5e7eb\'; this.style.background=\'' + (isSelected ? '#e0e7ff' : 'white') + '\';" class="' + (isSelected ? 'selected' : '') + '">';
        html += '<div style="flex: 1;"><span style="display: inline-block; width: 24px; height: 24px; line-height: 24px; text-align: center; background: #f3f4f6; border-radius: 4px; margin-right: 12px; font-size: 12px; font-weight: 600; color: #6b7280;">' + (i + 1) + '</span>';
        html += '<code style="background: #f9fafb; padding: 4px 8px; border-radius: 4px; font-size: 13px; font-family: \'Consolas\', \'Monaco\', monospace; color: #1f2937;">' + escapedRule + '</code></div>';
        html += '</div>';
    }
    html += '</div>';
    
    container.innerHTML = html;
}

function selectIpRuleRow(row, index) {
    if (typeof index === 'undefined') {
        var parent = row.parentNode;
        index = Array.from(parent.children).indexOf(row);
    }
    selectedIpRuleIndex = index;
    document.querySelectorAll('#ipRulesList > div > div').forEach(function(r) {
        r.style.backgroundColor = '';
        r.style.borderColor = '#e5e7eb';
        r.classList.remove('selected');
    });
    if (row) {
        row.style.backgroundColor = '#e0e7ff';
        row.style.borderColor = '#667eea';
        row.classList.add('selected');
    }
    var removeBtn = document.getElementById('btnRemoveIpRule');
    if (removeBtn) removeBtn.disabled = false;
}

function selectMacRuleRow(row, index) {
    if (typeof index === 'undefined') {
        index = Array.from(row.parentNode.children).indexOf(row);
    }
    selectedMacRuleIndex = index;
    document.querySelectorAll('#macRulesList > div > div').forEach(function(r) {
        r.style.backgroundColor = '';
        r.style.borderColor = '#e5e7eb';
        r.classList.remove('selected');
    });
    if (row) {
        row.style.backgroundColor = '#e0e7ff';
        row.style.borderColor = '#667eea';
        row.classList.add('selected');
    }
    var removeBtn = document.getElementById('btnRemoveMacRule');
    if (removeBtn) removeBtn.disabled = false;
}

function updateRestrictionEnabled(enabled) {
    fetch(getSystemApiBase() + '/restriction', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ enabled: enabled })
    })
    .then(function(response) {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(function(result) {
        if (result.success) {
            updateRestrictionControlsState(enabled);
        } else {
            alert('更新失败：' + (result.message || '未知错误'));
            // 恢复复选框状态
            var chk = document.getElementById('chkEnableRestriction');
            if (chk) chk.checked = !enabled;
        }
    })
    .catch(function(error) {
        alert('更新失败：' + error.message);
        // 恢复复选框状态
        var chk = document.getElementById('chkEnableRestriction');
        if (chk) chk.checked = !enabled;
    });
}

function updateRestrictionMode(whitelistMode) {
    var apiBase = typeof getSystemApiBase === 'function' ? getSystemApiBase() : '/api/system';
    fetch(apiBase + '/restriction', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ whitelistMode: whitelistMode })
    })
    .then(function(response) {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(function(result) {
        if (!result.success) {
            alert('更新失败：' + (result.message || '未知错误'));
            loadRestriction(); // 重新加载以恢复状态
        }
    })
    .catch(function(error) {
        alert('更新失败：' + error.message);
        loadRestriction(); // 重新加载以恢复状态
    });
}

function showAddIpRuleDialog() {
    var rule = prompt('请输入IP规则（支持单个IP、CIDR网段如192.168.1.0/24、IP范围如192.168.1.1-192.168.1.100）：');
    if (!rule || !rule.trim()) {
        return;
    }
    
    addIpRule(rule.trim());
}

function addIpRule(rule) {
    var apiBase = typeof getSystemApiBase === 'function' ? getSystemApiBase() : '/api/system';
    fetch(apiBase + '/restriction/ip', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ rule: rule })
    })
    .then(function(response) {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(function(result) {
        if (result.success) {
            loadRestriction();
        } else {
            alert('添加失败：' + (result.message || '未知错误'));
        }
    })
    .catch(function(error) {
        alert('添加失败：' + error.message);
    });
}

function removeSelectedIpRule() {
    if (selectedIpRuleIndex < 0) {
        alert('请先选择要删除的IP规则');
        return;
    }
    
    if (!confirm('确定要删除选中的IP规则吗？')) {
        return;
    }
    
    var apiBase = typeof getSystemApiBase === 'function' ? getSystemApiBase() : '/api/system';
    fetch(apiBase + '/restriction/ip/' + selectedIpRuleIndex, {
        method: 'DELETE'
    })
    .then(function(response) {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(function(result) {
        if (result.success) {
            selectedIpRuleIndex = -1;
            loadRestriction();
        } else {
            alert('删除失败：' + (result.message || '未知错误'));
        }
    })
    .catch(function(error) {
        alert('删除失败：' + error.message);
    });
}

function showAddMacRuleDialog() {
    var rule = prompt('请输入MAC规则（支持完整MAC地址如00:11:22:33:44:55或通配符如00:11:22:*:*:*）：', '00:11:22:33:44:55');
    if (!rule || !rule.trim()) {
        return;
    }
    
    addMacRule(rule.trim());
}

function addMacRule(rule) {
    // 标准化MAC地址格式
    rule = rule.toUpperCase().replace(/-/g, ':');
    
    var apiBase = typeof getSystemApiBase === 'function' ? getSystemApiBase() : '/api/system';
    fetch(apiBase + '/restriction/mac', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ rule: rule })
    })
    .then(function(response) {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(function(result) {
        if (result.success) {
            loadRestriction();
        } else {
            alert('添加失败：' + (result.message || '未知错误'));
        }
    })
    .catch(function(error) {
        alert('添加失败：' + error.message);
    });
}

function removeSelectedMacRule() {
    if (selectedMacRuleIndex < 0) {
        alert('请先选择要删除的MAC规则');
        return;
    }
    
    if (!confirm('确定要删除选中的MAC规则吗？')) {
        return;
    }
    
    var apiBase = typeof getSystemApiBase === 'function' ? getSystemApiBase() : '/api/system';
    fetch(apiBase + '/restriction/mac/' + selectedMacRuleIndex, {
        method: 'DELETE'
    })
    .then(function(response) {
        if (!response.ok) {
            throw new Error('HTTP ' + response.status);
        }
        return response.json();
    })
    .then(function(result) {
        if (result.success) {
            selectedMacRuleIndex = -1;
            loadRestriction();
        } else {
            alert('删除失败：' + (result.message || '未知错误'));
        }
    })
    .catch(function(error) {
        alert('删除失败：' + error.message);
    });
}

